/* eslint-disable no-constant-condition */
import { NavBar, InfiniteScroll, Popup } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './index.module.scss'
import DOMPurify from 'dompurify'
import Icon from '@/components/Icon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import useInitialState from '@/hooks/useInitialState'
import { getArticleDetail, getCommentList } from '@/store/actions/articleDetail'
import { relativeTime } from '@/utils'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import { useEffect, useRef, useState } from 'react'
import NoComment from './components/NoComment'
import CommentInput from './components/CommentInput'
const Article = () => {
  const history = useHistory()
  const obj = useParams<{id: string}>()
  const [isShowAuthor, setIsShowAuthor] = useState(false)
  const authorRef = useRef<HTMLDivElement>(null)
  const wrapRef = useRef<HTMLDivElement>(null)
  const commentRef = useRef<HTMLDivElement>(null)

  const { comment } = useInitialState(() => getCommentList(obj.id), 'articleDetail')
  console.log(comment)
  const { article } = useInitialState(() => getArticleDetail(obj.id), 'articleDetail')

  const pStr = '<img onerror="localStorage.removeItem(`itcast_geek_h5_history`)" src=""/>'
  console.log(DOMPurify.sanitize(pStr))

  useEffect(() => {
    const scrollCallback = () => {
      console.log('xxxx')
      // 获取 作者区域 距离页面顶部的距离
      const obj = authorRef.current?.getBoundingClientRect()
      console.log(obj)
      if (obj!.top < 50) {
        setIsShowAuthor(true)
      } else {
        setIsShowAuthor(false)
      }
    }
    wrapRef.current?.addEventListener('scroll', scrollCallback)
    return () => {
      console.log('组件销毁.....')
      wrapRef.current?.removeEventListener('scroll', scrollCallback)
    }
  }, [])

  useEffect(() => {
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true
    })
    // 获取到内容中所有的code标签
    const codes = document.querySelectorAll('.dg-html pre code')
    codes.forEach((el) => {
      // 让code进行高亮
      hljs.highlightElement(el as HTMLElement)
    })
  }, [article])
  // const pStr = ''
  const renderArticle = () => {
    // 文章详情
    return (
      <div className="wrapper" ref={wrapRef}>
        <div dangerouslySetInnerHTML={{ __html: pStr }}>

        </div>
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{article.title}</h1>

            <div className="info">
              <span>{article.pubdate}</span>
              <span>{article.read_count}阅读</span>
              <span>{article.comm_count}评论</span>
            </div>

            <div className="author" ref={authorRef}>
              <img src={article.aut_photo} alt="" />
              <span className="name">{article.aut_name}</span>
              <span className={classNames('follow', article.is_followed ? 'followed' : '')}>
                {article.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          </div>

          <div className="content">
            <div
              className="content-html dg-html"
              dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(article.content) }}
            />
            <div className="date">发布文章时间：{relativeTime(article.pubdate)}</div>
          </div>
        </div>

        <div className="comment" ref={commentRef}>
          <div className="comment-header">
            <span>全部评论（{comment.total_count}）</span>
            <span>20 点赞</span>
          </div>

          <div className="comment-list">
            {
              comment.total_count === 0
                ? <NoComment/>
                : (comment.results?.map(item => (<CommentItem key={item.com_id} comment={item}/>)))
            }
            {/* <NoComment/> */}
            {/* <CommentItem /> */}
            {/* <CommentItem /> */}

            {/* <InfiniteScroll
              hasMore={false}
              loadMore={async () => {
                console.log(1)
              }}
            /> */}
          </div>
        </div>
      </div>
    )
  }

  const onComment = () => {
    console.log('把父组件的滚动条，滚到一个位置，让评论区可见！')
    // 1. 找到评论区对应的dom，得到它的offsetTop
    // 2. 让外层容器，滚到这个位置
    const top = commentRef.current?.offsetTop || 0
    wrapRef.current?.scrollTo(0, top - 50)
  }

  // 评论表单显示状态
  const [commentShow, setCommentShow] = useState(false)
  const hideComment = () => {
    setCommentShow(false)
  }
  const showComment = () => {
    setCommentShow(true)
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {isShowAuthor && (
            <div className="nav-author">
              <img src={article.aut_photo} alt="" />
              <span className="name">{article.aut_name}</span>
              <span className={classNames('follow', article.is_followed ? 'followed' : '')}>
                {article.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter showComment={showComment} onComment={onComment}/>
      </div>
      <Popup visible={commentShow} position="right">
        <CommentInput hideComment={hideComment} artId={article.art_id}></CommentInput>
      </Popup>
    </div>
  )
}

export default Article
